const path = require("path");
const BaseHandler = require(path.join(__dirname, "../libs/baseHandler.js"));
const handler = new BaseHandler();
const Tags = require("../models/tag");
const _ = require("lodash");

// handler.getA=async function(ctx){
//   return handler.restSuccess(ctx, { res:'a' });
// }

handler.addTag = async function (ctx) {
  const { name, color, isIncome } = ctx.request.body;

  const isExists = await Tags.exists({ name });

  if (isExists) {
    throw new Error("该分类已存在!");
  }

  let query = {
    name: name.replace(/\s/g, ""),
    isIncome,
  };

  if (color) {
    query.color = color;
  }

  const tag = await Tags(query).save();
  return handler.restSuccess(ctx, tag);
};

handler.getTagsList = async function (ctx) {
  const { page = 1, pageSize = 10, created = -1 } = ctx.query;
  const condition = {};
  let { search = {} } = ctx.query;

  const searchCondition = [];
  if (_.get(search, "name")) {
    searchCondition.push({ name: _.get(search, "name") });
  }
  if (searchCondition.length > 0) {
    condition.$or = searchCondition;
  }

  const count = await Tags.count(condition);
  const list = await Tags.find(condition)
    .sort({ created })
    .skip((Number(page) - 1) * Number(pageSize))
    .limit(pageSize)
    .lean();

  return handler.restSuccess(ctx, { list, count });
};

handler.editTag = async function (ctx) {
  const { name, color, isIncome, id } = ctx.request.body;

  const isExists = await Tags.exists({ _id: id });

  if (!isExists) {
    throw new Error("该分类不存在!");
  }

  let query = {
    name: name.replace(/\s/g, ""),
    isIncome,
    id,
  };

  if (color) {
    query.color = color;
  }

  const tag = await Tags.updateOne({ _id: id }, { $set: query });
  return handler.restSuccess(ctx, tag);
};

handler.deleteTags = async function (ctx) {
  let { ids } = ctx.request.body;
  ids = JSON.parse(ids);
  if (_.isEmpty(ids)) {
    throw new Error("请选择要删除的分类！");
  }

  const result = await Tags.deleteMany({ _id: { $in: ids } });
  handler.restSuccess(ctx, { result });
};

module.exports = handler;
